<template>
  <view class="register-container">
    <!-- 自定义导航栏 -->
    <u-navbar 
      title="用户注册"
      :background="{ background: 'transparent' }"
      :title-style="{ color: 'white' }"
      left-icon-color="white"
      @leftClick="goBack"
    />
    
    <!-- 注册表单 -->
    <view class="form-section">
      <view class="form-container card">
        <view class="form-title">
          <text class="title-text">创建账号</text>
          <text class="subtitle-text">请填写以下信息完成注册</text>
        </view>
        
        <u-form :model="form" ref="formRef" label-width="0">
          <!-- 用户名 -->
          <u-form-item prop="username">
            <u-input
              v-model="form.username"
              placeholder="请输入用户名"
              maxlength="20"
              :border="false"
              :custom-style="inputStyle"
            >
              <template #prefix>
                <u-icon name="account" size="20" color="#999"></u-icon>
              </template>
            </u-input>
          </u-form-item>
          
          <!-- 手机号 -->
          <u-form-item prop="mobile">
            <u-input
              v-model="form.mobile"
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
              :border="false"
              :custom-style="inputStyle"
            >
              <template #prefix>
                <u-icon name="phone" size="20" color="#999"></u-icon>
              </template>
            </u-input>
          </u-form-item>
          
    
          
          <!-- 密码 -->
          <u-form-item prop="password">
            <u-input
              v-model="form.password"
              placeholder="请输入密码(6-20位)"
              :password="!showPassword"
              :border="false"
              :custom-style="inputStyle"
            >
              <template #prefix>
                <u-icon name="lock" size="20" color="#999"></u-icon>
              </template>
              <template #suffix>
                <u-icon 
                  :name="showPassword ? 'eye-off' : 'eye'" 
                  size="20" 
                  color="#999"
                  @click="showPassword = !showPassword"
                ></u-icon>
              </template>
            </u-input>
          </u-form-item>
          
          <!-- 确认密码 -->
          <u-form-item prop="confirmPassword">
            <u-input
              v-model="form.confirmPassword"
              placeholder="请再次输入密码"
              :password="!showConfirmPassword"
              :border="false"
              :custom-style="inputStyle"
            >
              <template #prefix>
                <u-icon name="lock" size="20" color="#999"></u-icon>
              </template>
              <template #suffix>
                <u-icon 
                  :name="showConfirmPassword ? 'eye-off' : 'eye'" 
                  size="20" 
                  color="#999"
                  @click="showConfirmPassword = !showConfirmPassword"
                ></u-icon>
              </template>
            </u-input>
          </u-form-item>
          
          <!-- 用户类型选择 -->
          <u-form-item prop="role">
            <view class="role-selector">
              <text class="role-label">我是：</text>
              <u-radio-group v-model="form.role" placement="row">
                <u-radio 
                  :name="'PARENT'"
                  :custom-style="{ marginRight: '40rpx' }"
                >
                  家长
                </u-radio>
                <u-radio :name="'TEACHER'">
                  教员
                </u-radio>
              </u-radio-group>
            </view>
          </u-form-item>
        </u-form>
        
  
        <!-- 注册按钮 -->
        <u-button
          type="primary"
          :loading="loading"
          :custom-style="buttonStyle"
          @click="handleRegister"
        >
          注册
        </u-button>
        
        <!-- 登录链接 -->
        <view class="login-link">
          <text>已有账号？</text>
          <text class="link-text" @click="goToLogin">立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { register, sendSmsCode } from '@/api/auth'
import { setToken, setUserInfo } from '@/utils/auth'

export default {
  data() {
    return {
      form: {
        username: '',
        mobile: '',
        code: '',
        password: '',
        confirmPassword: '',
        role: 'PARENT'
      },
      showPassword: false,
      showConfirmPassword: false,
      loading: false,
      codeLoading: false,
      codeDisabled: false,
      codeText: '获取验证码',
      agreementChecked: false,
      countdown: 60,
      inputStyle: {
        backgroundColor: '#f8f9fa',
        borderRadius: '12rpx',
        padding: '24rpx',
        marginBottom: '20rpx'
      },
      buttonStyle: {
        borderRadius: '50rpx',
        height: '90rpx',
        marginTop: '40rpx',
        background: 'linear-gradient(45deg, #5daf34, #3cc51f)'
      },
      codeButtonStyle: {
        borderRadius: '20rpx',
        height: '60rpx',
        minWidth: '140rpx'
      }
    }
  },
  
  methods: {
    // 发送验证码
    async sendCode() {
      if (!this.form.mobile) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.form.mobile)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return
      }
      
      this.codeLoading = true
      
      try {
        await sendSmsCode({
          mobile: this.form.mobile,
          type: 'REGISTER'
        })
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        // 开始倒计时
        this.startCountdown()
        
      } catch (error) {
        console.error('发送验证码失败:', error)
      } finally {
        this.codeLoading = false
      }
    },
    
    // 倒计时
    startCountdown() {
      this.codeDisabled = true
      this.countdown = 60
      
      const timer = setInterval(() => {
        this.countdown--
        this.codeText = `${this.countdown}s后重发`
        
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeDisabled = false
          this.codeText = '获取验证码'
        }
      }, 1000)
    },
    
    // 处理注册
    async handleRegister() {
      if (!this.validateForm()) {
        return
      }
      
  
      this.loading = true
      
      try {
        const response = await register({
          username: this.form.username,
          mobile: this.form.mobile,
          password: this.form.password,
          role: this.form.role
        })
        
        const { token, userId, username, roles } = response.data
        
        // 保存登录信息
        setToken(token)
        setUserInfo({
          userId,
          username,
          roles,
          mobile: this.form.mobile
        })
        
        uni.showToast({
          title: '注册成功',
          icon: 'success'
        })
        
        // 跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 1000)
        
      } catch (error) {
        console.error('注册失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 表单验证
    validateForm() {
      if (!this.form.username) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      
      if (this.form.username.length < 3 || this.form.username.length > 20) {
        uni.showToast({
          title: '用户名长度为3-20个字符',
          icon: 'none'
        })
        return false
      }
      
      if (!this.form.mobile) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return false
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.form.mobile)) {
        uni.showToast({
          title: '手机号格式不正确',
          icon: 'none'
        })
        return false
      }
    
 
      if (!this.form.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return false
      }
      
      if (this.form.password.length < 6 || this.form.password.length > 20) {
        uni.showToast({
          title: '密码长度为6-20位',
          icon: 'none'
        })
        return false
      }
      
      if (this.form.password !== this.form.confirmPassword) {
        uni.showToast({
          title: '两次密码输入不一致',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 返回
    goBack() {
      uni.navigateBack()
    },
    
    // 跳转到登录页
    goToLogin() {
      uni.navigateBack()
    },
    
    // 显示用户协议
    showAgreement() {
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    },
    
    // 显示隐私政策
    showPrivacy() {
      uni.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  padding-bottom: 40rpx;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="10" cy="90" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
  }
}

.form-section {
  margin-top: 200rpx;
  padding: 0 40rpx;
  
  .form-container {
    padding: 60rpx 40rpx;
    border-radius: 30rpx;
    background: white;
    box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
    position: relative;
    z-index: 1;
    .form-title {
      text-align: center;
      margin-bottom: 60rpx;
      
      .title-text {
        display: block;
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .subtitle-text {
        display: block;
        font-size: 28rpx;
        color: #666;
      }
    }
    
    .code-input-wrapper {
      display: flex;
      align-items: center;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      
      .u-input {
        flex: 1;
      }
    }
    
    .role-selector {
      display: flex;
      align-items: center;
      padding: 24rpx;
      background-color: #f8f9fa;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      
      .role-label {
        font-size: 28rpx;
        color: #666;
        margin-right: 30rpx;
      }
    }
    
    .agreement-section {
      display: flex;
      align-items: flex-start;
      margin-top: 30rpx;
      
      .agreement-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.5;
        
        .link-text {
          color: #3cc51f;
        }
      }
    }
    
    .login-link {
      text-align: center;
      margin-top: 40rpx;
      font-size: 28rpx;
      color: #666;
      
      .link-text {
        color: #3cc51f;
        margin-left: 10rpx;
      }
    }
  }
}
</style> 